package com.hncboy.chatgpt.front.mongodb;

import cn.hutool.json.JSONUtil;
import com.hncboy.chatgpt.base.domain.mongodb.TextParsing;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.util.List;

@Slf4j
@Component
public class TextParsingMapper {

    @Resource
    MongoTemplate mongoTemplate;

    public List<TextParsing> selectByKeyword(String keyword) {
        Query query = new Query(Criteria.where("keyword").is(keyword.trim()));
        return mongoTemplate.find(query, TextParsing.class);
    }

    public TextParsing selectByEmailAndCode(String email, String code) {
        Query query = new Query(Criteria.where("email")
                .is(email).and("context").is(code).and("status").is(true));
        return mongoTemplate.findOne(query, TextParsing.class);
    }

    public TextParsing selectByEmailFirst(String email) {
        Query query = new Query(Criteria.where("email")
                .is(email).and("status").is(true));
        query.with(Sort.by(Sort.Order.desc("create_date"))).limit(1);
        return mongoTemplate.findOne(query, TextParsing.class);
    }

    public TextParsing insert(TextParsing textParsing) {
        return mongoTemplate.insert(textParsing);
    }


    private Update objToUpdate(TextParsing po) {
        Update update = new Update();
        Class<?> clazz = po.getClass();
        for (Field field : clazz.getDeclaredFields()) {
            field.setAccessible(true);
            String fieldName = field.getName();
            try {
                if (null != field.get(po)) {
                    update.set(fieldName, field.get(po));
                }
            } catch (IllegalAccessException e) {
                log.error("objToUpdate param:{}", JSONUtil.toJsonStr(po), e);
            }
        }
        return update;
    }

}
